package com.example.smartcity_poverty.ui.PersonalCenter.activity

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import com.example.smartcity_poverty.App
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.network.AppApi
import com.example.smartcity_poverty.logic.network.ServiceNET.Companion.create
import com.example.smartcity_poverty.logic.util.Util.show
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 用户登录模块
 */
class LoginActivity : AppCompatActivity() {


    // 登录/注册状态
    var isLogin = false

    // 动画周期
    var mDuration: Long = 300L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_login)
        title = "登录"
        // 弄个动画
        startAnimationUI()

        onBtnClick()

    }

    /**
     * 弄个动画
     */
    private fun startAnimationUI() {
        alOne.animation = App.getAnimationLogin()
        EdLoginUserPassword.animation = App.getAnimationLogin()
        EdLoginUserName.animation = App.getAnimationLogin()
        LoginBtn.animation = App.getAnimationLogin()

        tvAnimation1.animation = App.getAnimationLeftAndEnd()
        tvAnimation2.animation = App.getAnimationLeftAndEnd()
    }


    /**
     * 事件
     */
    private fun onBtnClick() {
        // 按钮点击事件
        LoginBtn.setOnClickListener {
            // 根据按钮文本调用不同的函数
            if (LoginBtn.text.toString() == "登录") {
                // 登录
                login(EdLoginUserName.text.toString(), EdLoginUserPassword.text.toString())
            }

            // 注册
            if (LoginBtn.text == "注册") {
                // 传入参数
                newLogin(
                    edNewLoginUserName.text.toString(),
                    edNewLoginUserPwd.text.toString(),
                    edNewLoginUserPhone.text.toString()
                )
            }
        }

        // 点击切换登录
        newLogin.setOnClickListener {
            if (LoginBtn.text.toString() == "登录") {
                runOnUiThread {
                    loginAndNewLogin(false)
                    LoginBtn.text = "注册"
                }

            } else {
                runOnUiThread {
                    loginAndNewLogin(true)
                    LoginBtn.text = "登录"
                }

            }
        }
    }

    /**
     * 切换登录
     * @param isLogin true为登录布局 / false为注册布局
     */
    private fun loginAndNewLogin(isLogin: Boolean = true) {
        when(isLogin) {
            true -> {
                // 隐藏注册布局
                newLoginLayout.visibility = View.GONE
                //  显示登录布局
                loginLayout.visibility = View.VISIBLE
            }
            false -> {
                // 隐藏登录布局
                loginLayout.visibility = View.GONE
                // 显示注册布局
                newLoginLayout.visibility = View.VISIBLE
            }
        }
    }


    /**
     * 登录
     */
    private fun login(userName: String, userPassword: String) {
        // 判断是否为空
        if (userName.isEmpty() && userPassword.isEmpty()) {
            "账号或密码未输入...".show()
            return
        }

        // 登录
        coroutine(Dispatchers.Main) {
            create<AppApi>().login(JSONObject().apply {
                put("username", userName)
                put("password", userPassword)
            }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                if (this.code == "200") {
                    "登录成功!".show()

                    // 存储token和登录状态
                    getSharedPreferences("token", Context.MODE_PRIVATE)
                        .edit()
                        .putBoolean("user", true)
                        .putString("token", this.token)
                        .apply()
                    // 销毁该登录意图
                    finish()
                } else this.msg.show()
            }
        }
    }


    /**
     * 注册
     */
    private fun newLogin(uName: String, uPwd: String, uPhone: String) {
        // 判断是否为空
        if (uName.isEmpty() && uPwd.isEmpty()) {
            "账号或密码未输入...".show()
            return
        }

        // 判断号码是否是11位数
        if (uPhone.length <= 10) {
            "号码不存!".show()
            return
        }

        // 开启协程
        coroutine {
            // 准备数据
            val uData = JSONObject().apply {
                put("userName", uName)
                put("password", uPwd)
                put("phonenumber", uPhone)
                put("sex", 0) // 默认性别为男
            }.toString().toRequestBody("application/json".toMediaTypeOrNull())

            // 发起网络请求
            val newLoginResponse = api.newLogin(uData)

            runOnUiThread {
                // 获取响应的数据判断是否注册成功
                if (newLoginResponse.code == "200") {
                    "注册成功!".show()
                    // 注册成功后我们销毁该意图
                    // 然后登录
                    login(uName, uPwd)
                    finish()
                } else newLoginResponse.msg.toString().show()
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}